using System.Collections;
using System.Collections.Generic;
using UnityEditor;

/// <summary>
/// 
/// </summary>
public static class XEditorCoroutineRunner
{
    /// <summary>
    /// 
    /// </summary>
    private static readonly List<XEditorCoroutine> croutines = new List<XEditorCoroutine>();
    /// <summary>
    /// 
    /// </summary>
    private static readonly List<IEnumerator>
        buffer = new List<IEnumerator>();

    /// <summary>
    /// 
    /// </summary>
    /// <param name="iterator"></param>
    /// <returns></returns>
    public static IEnumerator StartEditorCoroutine(IEnumerator iterator)
    {
        if (croutines.Count == 0)
        {
            EditorApplication.update += Update;
        }

        buffer.Add(iterator);

        return iterator;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="iterator"></param>
    /// <returns></returns>
    private static bool Find(IEnumerator iterator)
    {
        foreach (XEditorCoroutine editorCoroutine in croutines)
        {
            if (editorCoroutine.Find(iterator))
            {
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// 
    /// </summary>
    private static void Update()
    {
        croutines.RemoveAll(
            coroutine => { return coroutine.MoveNext() == false; }
        );

        if (buffer.Count > 0)
        {
            foreach (IEnumerator iterator in buffer)
            {
                if (!Find(iterator))
                {
                    croutines.Add(new XEditorCoroutine(iterator));
                }
            }

            buffer.Clear();
        }

        if (croutines.Count == 0)
        {
            EditorApplication.update -= Update;
        }
    }
}
